package calvin.listener;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import calvin.datastore.model.Rate;
import calvin.utils.RateCache;

public class SimpleRateListener implements RateListener {
    
    private static final Logger logger = Logger.getLogger(SimpleRateListener.class
        .getName());
    
    private static Map<String, Double> watchMap = new HashMap<String, Double>();

    public void dealTick() throws Exception {

        for (Map.Entry<String, Double> e : watchMap.entrySet()) {
            String key = e.getKey();
            String[] array = key.split("|");
            String cp = array[0];
            short side = Short.valueOf(array[1]);
            double v = e.getValue();
            Rate rate = RateCache.get(cp);
            if((side == 1 && v < rate.b)
                    ||(side == -1 && v > rate.a) ) {
                sendAlertMail(cp, v, side);
                SimpleRateListener.clearAlert(cp, side);
            }
            
        }
    }

    public static synchronized void clearAlert(String cp, short side) {
        watchMap.remove(cp + "|" + side);
    }

    public static synchronized void setAlert(String cp, short side, double v) {
        watchMap.put(cp + "|" + side, v);
    }
    
    private void sendAlertMail(String cp, double v, short side) throws Exception {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("calvin.helloworld@gmail.com", "Admin"));
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress("calvin.helloworld@gmail.com", "Calvin"));
            StringBuilder sb = new StringBuilder();
            sb.append(cp)
                .append(" hit your expect trade price: ")
                .append(cp)
                .append(side == 1 ? "   buy  " : "sell  ")
                .append(v);
            msg.setSubject(sb.toString());
            Transport.send(msg);
    
        } catch (Exception e) {
            logger.log(
                Level.SEVERE,
                "failed to send alert mail to Calvin." + e.getMessage());
        }
    }
}
